/*
        Creator:Craig Shoemaker 
        blog url:http://www.codemag.com/Article/1411041
        Modify by:Wolfy
        blog url:http://www.cnblogs.com/wolf-sun/
        git:http://git.oschina.net/wolfy/indexed-store-db

*/
;
window.indexedDB = window.indexedDB ||
                   window.mozIndexedDB ||
                   window.webkitIndexedDB ||
                   window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction ||
                   window.webkitIDBTransaction ||
                   window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange ||
                   window.webkitIDBKeyRange ||
                   window.msIDBKeyRange;
(function (window) {
    'use strict';
    var db = {
        version: 1, // important: only use whole numbers!
        isSupport: function () {// support indexeddb or not
            if (!window.indexedDB)
                return false;
            return true;
        },
        objectStoreName: 'app_test',
        instance: {},
        upgrade: function (e) {
            var _db = e.target.result,
                names = _db.objectStoreNames,
                name = db.objectStoreName;
            if (!names.contains(name)) {
                _db.createObjectStore(
                    name,
                    {
                        keyPath: 'id',
                        autoIncrement: true
                    });
            }
        },
        errorHandler: function (error) {
            window.alert('error: ' + error.target.code);
            debugger;
        },
        open: function (callback) {
            var request = window.indexedDB.open(
                db.objectStoreName, db.version);
            request.onerror = db.errorHandler;
            request.onupgradeneeded = db.upgrade;
            request.onsuccess = function (e) {
                db.instance = request.result;
                db.instance.onerror = db.errorHandler;
                callback();
            };
        },
        getObjectStore: function (mode) {
            var txn, store;
            mode = mode || 'readonly';
            txn = db.instance.transaction([db.objectStoreName], mode);
            store = txn.objectStore(db.objectStoreName);
            return store;
        },
        save: function (data, callback) {
            if (db.isSupport()) {
                db.open(function () {
                    var store, request, mode = 'readwrite';
                    store = db.getObjectStore(mode),
                    request = data.id ?
                        store.put(data) :
                        store.add(data);
                    request.onsuccess = callback;
                });
            } else {
                window.localStorage.setItem(data.id, JSON.stringify(data));
            };

        },
        getAll: function (callback) {
            if (db.isSupport()) {
                db.open(function () {
                    var store = db.getObjectStore(),
                        cursor = store.openCursor(),
                        data = [];
                    cursor.onsuccess = function (e) {
                        var result = e.target.result;
                        if (result && result !== null) {
                            data.push(result.value);
                            result.continue();
                        } else {
                            callback(data);
                        }
                    };
                });
            } else {
                var arr = [];
                for (var i = 0; i < window.localStorage.length; i++) {
                    var key = window.localStorage.key(i);
                    if (key !== "oldtoken") {
                        var strJson = window.localStorage.getItem(key);
                        var result = null;
                        if (strJson) {
                            try {
                                result = JSON.parse(strJson);
                            } catch (e) {

                            }
                        };
                        if (result) {
                            arr.push(result);
                        };
                    };

                };
                callback(arr);
            };

        },
        get: function (id, callback) {
            if (db.isSupport()) {
                db.open(function () {
                    var
                        store = db.getObjectStore(),
                        request = store.get(id);
                    request.onsuccess = function (e) {
                        callback(e.target.result);
                    };
                });
            } else {
                var strJson = window.localStorage.getItem(id);
                var result = null;
                if (strJson) {
                    try {
                        result = JSON.parse(strJson);
                    } catch (e) {

                    }
                };
                callback(result);
            };

        },
        'delete': function (id, callback) {
            if (db.isSupport()) {
                db.open(function () {
                    var
                        mode = 'readwrite',
                        store, request;
                    store = db.getObjectStore(mode);
                    request = store.delete(id);
                    request.onsuccess = callback;
                });
            } else {
                window.localStorage.removeItem(id);
            };

        },
        deleteAll: function (callback) {
            if (db.isSupport()) {
                db.open(function () {
                    var mode, store, request;
                    mode = 'readwrite';
                    store = db.getObjectStore(mode);
                    request = store.clear();
                    request.onsuccess = callback;
                });
            } else {
                window.localStorage.clear();
            }
        },
        clearByToke: function (newtoken) {
            //是否更换用户
            var oldtoken = window.localStorage.getItem("oldtoken");
            if (oldtoken && oldtoken !== newtoken) {
                window.localStorage.clear();
                if (db.isSupport()) {
                    db.deleteAll();
                };
            };
            window.localStorage.setItem("oldtoken", newtoken);
        }
    };
    window.app = window.app || {};
    window.app.db = db;
}(window));